/**
 * 动态代理配置工具
 * 根据环境变量动态生成代理配置
 */

/**
 * 创建动态代理配置
 * @param {Object} env 环境变量对象
 * @returns {Object} 代理配置对象
 */
export function createProxy(env) {
  const proxy = {};

  // 基础API代理
  if (env.VITE_API_BASE_URL) {
    proxy['/api'] = {
      target: env.VITE_API_BASE_URL,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true',
      rewrite: (path) => path.replace(/^\/api/, '/api'),
      configure: (proxy, options) => {
        proxy.on('proxyReq', (proxyReq, req, res) => {
          console.log(`[PROXY] ${req.method} ${req.url} -> ${proxyReq.path}`);
        });
        proxy.on('proxyRes', (proxyRes, req, res) => {
          console.log(`[PROXY] ${req.method} ${req.url} -> ${proxyRes.statusCode}`);
        });
      }
    };
  }

  // 用户服务代理
  if (env.VITE_USER_API_URL) {
    proxy['/api/user'] = {
      target: env.VITE_USER_API_URL,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true',
      rewrite: (path) => path.replace(/^\/api\/user/, '/user')
    };
  }

  // 商品服务代理
  if (env.VITE_PRODUCT_API_URL) {
    proxy['/api/product'] = {
      target: env.VITE_PRODUCT_API_URL,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true',
      rewrite: (path) => path.replace(/^\/api\/product/, '/product')
    };
  }

  // 订单服务代理
  if (env.VITE_ORDER_API_URL) {
    proxy['/api/order'] = {
      target: env.VITE_ORDER_API_URL,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true',
      rewrite: (path) => path.replace(/^\/api\/order/, '/order')
    };
  }

  // 文件上传代理
  if (env.VITE_UPLOAD_API_URL) {
    proxy['/api/upload'] = {
      target: env.VITE_UPLOAD_API_URL,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true',
      rewrite: (path) => path.replace(/^\/api\/upload/, '/upload')
    };
  }

  // WebSocket代理
  if (env.VITE_WS_URL) {
    proxy['/ws'] = {
      target: env.VITE_WS_URL,
      ws: true,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true'
    };
  }

  // 第三方API代理
  if (env.VITE_EXTERNAL_API_URL) {
    proxy['/api/external'] = {
      target: env.VITE_EXTERNAL_API_URL,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true',
      rewrite: (path) => path.replace(/^\/api\/external/, ''),
      headers: {
        'Authorization': `Bearer ${env.VITE_EXTERNAL_API_TOKEN || 'your-token-here'}`
      }
    };
  }

  return proxy;
}

/**
 * 创建Webpack代理配置
 * @param {Object} env 环境变量对象
 * @returns {Object} Webpack代理配置对象
 */
export function createWebpackProxy(env) {
  const proxy = {};

  // 基础API代理
  if (env.VITE_API_BASE_URL) {
    proxy['/api'] = {
      target: env.VITE_API_BASE_URL,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true',
      pathRewrite: {
        '^/api': '/api'
      },
      onProxyReq: (proxyReq, req, res) => {
        console.log(`[PROXY] ${req.method} ${req.url} -> ${proxyReq.path}`);
      },
      onProxyRes: (proxyRes, req, res) => {
        console.log(`[PROXY] ${req.method} ${req.url} -> ${proxyRes.statusCode}`);
      }
    };
  }

  // 用户服务代理
  if (env.VITE_USER_API_URL) {
    proxy['/api/user'] = {
      target: env.VITE_USER_API_URL,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true',
      pathRewrite: {
        '^/api/user': '/user'
      }
    };
  }

  // 商品服务代理
  if (env.VITE_PRODUCT_API_URL) {
    proxy['/api/product'] = {
      target: env.VITE_PRODUCT_API_URL,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true',
      pathRewrite: {
        '^/api/product': '/product'
      }
    };
  }

  // 订单服务代理
  if (env.VITE_ORDER_API_URL) {
    proxy['/api/order'] = {
      target: env.VITE_ORDER_API_URL,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true',
      pathRewrite: {
        '^/api/order': '/order'
      }
    };
  }

  // 文件上传代理
  if (env.VITE_UPLOAD_API_URL) {
    proxy['/api/upload'] = {
      target: env.VITE_UPLOAD_API_URL,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true',
      pathRewrite: {
        '^/api/upload': '/upload'
      }
    };
  }

  // WebSocket代理
  if (env.VITE_WS_URL) {
    proxy['/ws'] = {
      target: env.VITE_WS_URL,
      ws: true,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true'
    };
  }

  // 第三方API代理
  if (env.VITE_EXTERNAL_API_URL) {
    proxy['/api/external'] = {
      target: env.VITE_EXTERNAL_API_URL,
      changeOrigin: env.VITE_PROXY_CHANGE_ORIGIN !== 'false',
      secure: env.VITE_PROXY_SECURE === 'true',
      pathRewrite: {
        '^/api/external': ''
      },
      headers: {
        'Authorization': `Bearer ${env.VITE_EXTERNAL_API_TOKEN || 'your-token-here'}`
      }
    };
  }

  return proxy;
}

/**
 * 创建代理配置验证
 * @param {Object} proxy 代理配置对象
 * @returns {Object} 验证结果
 */
export function validateProxy(proxy) {
  const errors = [];
  const warnings = [];

  Object.entries(proxy).forEach(([path, config]) => {
    // 检查必需配置
    if (!config.target) {
      errors.push(`代理路径 ${path} 缺少 target 配置`);
    }

    // 检查URL格式
    if (config.target && !isValidUrl(config.target)) {
      errors.push(`代理路径 ${path} 的 target 格式不正确: ${config.target}`);
    }

    // 检查WebSocket配置
    if (path.startsWith('/ws') && !config.ws) {
      warnings.push(`WebSocket代理路径 ${path} 建议添加 ws: true 配置`);
    }

    // 检查安全配置
    if (config.target && config.target.startsWith('https://') && config.secure === false) {
      warnings.push(`HTTPS代理路径 ${path} 建议设置 secure: true`);
    }
  });

  return {
    valid: errors.length === 0,
    errors,
    warnings
  };
}

/**
 * 验证URL格式
 * @param {string} url URL字符串
 * @returns {boolean} 是否有效
 */
function isValidUrl(url) {
  try {
    new URL(url);
    return true;
  } catch {
    return false;
  }
}

/**
 * 创建代理配置文档
 * @param {Object} proxy 代理配置对象
 * @returns {string} 配置文档
 */
export function generateProxyDocs(proxy) {
  let docs = '# 代理配置文档\n\n';
  
  Object.entries(proxy).forEach(([path, config]) => {
    docs += `## ${path}\n\n`;
    docs += `- **目标地址**: ${config.target}\n`;
    docs += `- **跨域**: ${config.changeOrigin ? '是' : '否'}\n`;
    docs += `- **安全**: ${config.secure ? '是' : '否'}\n`;
    
    if (config.rewrite) {
      docs += `- **路径重写**: ${config.rewrite.toString()}\n`;
    }
    
    if (config.pathRewrite) {
      docs += `- **路径重写**: ${JSON.stringify(config.pathRewrite)}\n`;
    }
    
    if (config.ws) {
      docs += `- **WebSocket**: 是\n`;
    }
    
    if (config.headers) {
      docs += `- **请求头**: ${JSON.stringify(config.headers)}\n`;
    }
    
    docs += '\n';
  });
  
  return docs;
}
